home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 5 / Skunkware 5.iso / lib / calc / solve.cal < prev    next >
Text File  |  1995-07-17  |  1KB  |  49 lines

  1. /*
  2.  * Copyright (c) 1993 David I. Bell
  3.  * Permission is granted to use, distribute, or modify this source,
  4.  * provided that this copyright notice remains intact.
  5.  *
  6.  * Solve the equation f(x) = 0 to within the desired error value for x.
  7.  * The function 'f' must be defined outside of this routine, and the low
  8.  * and high values are guesses which must produce values with opposite signs.
  9.  */
  10.  
  11. define solve(low, high, epsilon)
  12. {
  13.     local flow, fhigh, fmid, mid, places;
  14.  
  15.     if (isnull(epsilon))
  16.         epsilon = epsilon();
  17.     if (epsilon <= 0)
  18.         quit "Non-positive epsilon value";
  19.     places = highbit(1 + int(1/epsilon)) + 1;
  20.     flow = f(low);
  21.     if (abs(flow) < epsilon)
  22.         return low;
  23.     fhigh = f(high);
  24.     if (abs(flow) < epsilon)
  25.         return high;
  26.     if (sgn(flow) == sgn(fhigh))
  27.         quit "Non-opposite signs";
  28.     while (1) {
  29.         mid = bround(high - fhigh * (high - low) / (fhigh - flow), places);
  30.         if ((mid == low) || (mid == high))
  31.             places++;
  32.         fmid = f(mid);
  33.         if (abs(fmid) < epsilon)
  34.             return mid;
  35.         if (sgn(fmid) == sgn(flow)) {
  36.             low = mid;
  37.             flow = fmid;
  38.         } else {
  39.             high = mid;
  40.             fhigh = fmid;
  41.         }
  42.     }
  43. }
  44.  
  45. global lib_debug;
  46. if (lib_debug >= 0) {
  47.     print "solve(low, high, epsilon) defined";
  48. }
  49.